package com.addplus.townmall.server.queue_consumer.consumer;

import com.addplus.townmall.server.api.constant.ErrorCode;
import com.addplus.townmall.server.api.constant.StringConstant;
import com.addplus.townmall.server.api.exception.ErrorException;
import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.town.*;
import com.addplus.townmall.server.api.model.town.expand.WxPayOrderNotifyResultExpand;
import com.addplus.townmall.server.api.model.town.param.AliPayNotifyParam;
import com.addplus.townmall.server.api.model.town.param.ShopProductStockManagerParam;
import com.addplus.townmall.server.api.mongodao.AliPayOrderNotifyResultExpandDao;
import com.addplus.townmall.server.api.mongodao.ShopSkuModelDao;
import com.addplus.townmall.server.api.mongodao.WxPayOrderNotifyResultExpandDao;
import com.addplus.townmall.server.api.service.queue.GiftCardCreateService;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import org.apache.tomcat.jni.Error;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类名: ShopProductStockManagerConsumer
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/10/7 下午4:27
 * @description 类描述: 商品库存加减消费队列
 */
@Component
@RabbitListener(queues = "stock_manager_queue")
public class ShopProductStockManagerConsumer {

    private Logger logger = LoggerFactory.getLogger(ShopProductStockManagerConsumer.class);


    @Autowired
    private ShopSpecificationSkuMapper specificationSkuMapper;

    @Autowired
    private ShopProductMapper shopProductMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private CouponMemberRecordMapper couponMemberRecordMapper;

    @Autowired
    private ShopSkuModelDao shopSkuModelDao;

    @Autowired
    private SpikeActiveShopMapper spikeActiveShopMapper;

    @Autowired
    private OrderPayMapper orderPayMapper;

    @Autowired
    private GiftMemberCardMapper giftMemberCardMapper;

    @Autowired
    private GiftMemberCardRecordMapper memberCardRecordMapper;

    @Autowired
    private WxPayOrderNotifyResultExpandDao wxPayOrderNotifyResultDao;

    @Autowired
    private AliPayOrderNotifyResultExpandDao aliPayOrderNotifyResultExpandDao;

    @Reference(check = false, async = true)
    private GiftCardCreateService giftCardCreateService;

    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void process(ShopProductStockManagerParam stockManagerParam) throws IOException {
        if (stockManagerParam == null) {
            logger.error("stockManagerParam 入参参数为null");
            return;
        }
        //处理订单减库存
        if (stockManagerParam.getType() == 1) {
            this.orderStock(stockManagerParam);
        } else if (stockManagerParam.getType() == 2) {
            this.orderTimeOut(stockManagerParam);
        } else if (stockManagerParam.getType() == 3) {
            this.orderCancel(stockManagerParam);
        } else if (stockManagerParam.getType() == 4) {
            this.weChatSuccessNotify(stockManagerParam);
        } else if (stockManagerParam.getType() == 5) {
            this.aliPaySuccessNotify(stockManagerParam);
        } else {
            logger.error("stockManagerParam 类型错误,数据未：" + JSON.toJSONString(stockManagerParam));
        }
        logger.info("订单消息记录：" + JSON.toJSONString(stockManagerParam));
    }

    private void aliPaySuccessNotify(ShopProductStockManagerParam stockManagerParam) {
        if(DataUtils.isEmptyObject(stockManagerParam)){
            logger.error("入参参数为空");
        }
        AliPayNotifyParam aliPayNotifyParam = JSONObject.parseObject(stockManagerParam.getAliPayNotifyMsg(), AliPayNotifyParam.class);
        aliPayOrderNotifyResultExpandDao.insert(aliPayNotifyParam);
        if (aliPayNotifyParam == null) {
            logger.error("订单支付回调，获取回调信息为空，回调信息：" + stockManagerParam.getAliPayNotifyMsg());
            return;
        }
        // 获取对应商品父订单
        String orderParentNum = aliPayNotifyParam.getOutTradeNo();

        // 获取对应商品父订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_parent_number", orderParentNum);
        orderQueryWrapper.eq("is_delete", 0);
        List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
        if (orderList == null || orderList.isEmpty()) {
            logger.error("订单支付回调，查询原有订单失败，订单号：" + aliPayNotifyParam.getOutTradeNo());
            return;
        } else {
            List<Integer> orderIdList = orderList.stream().map(order -> order.getId()).collect(Collectors.toList());
            // 查询是否已经执行过了
            QueryWrapper<OrderPay> payQueryWrapper = new QueryWrapper<>();
            payQueryWrapper.in("order_id", orderIdList);
            payQueryWrapper.eq("type", 1);
            int orderPayCount = orderPayMapper.selectCount(payQueryWrapper);
            if (orderPayCount == orderList.size()) {
                logger.error("订单支付回调，当前订单已经执行，订单号：" + aliPayNotifyParam.getOutTradeNo());
                return;
            }
            // 检查当前订单金额是否一致
            BigDecimal totalAmount = orderList.stream().map(Order::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            String totalAmountInt = totalAmount.toString();
            if (!totalAmountInt.equals(aliPayNotifyParam.getTotalAmount().toString())) {
                logger.error("订单支付回调，支付金额和入参金额不一致，订单号" + aliPayNotifyParam.getOutTradeNo());
                // 添加商城订单支付表
                orderList.forEach(o -> {
                    OrderPay orderPay = new OrderPay();
                    orderPay.setOrderId(o.getId());
                    orderPay.setPayTypeId(1);
                    orderPay.setType(1);
                    orderPay.setPayNumber(aliPayNotifyParam.getTradeNo());
                    orderPay.setPayStatus(1);
                    orderPay.setPayRemark("支付金额不一致");
                    orderPay.setGmtCreate(new Date());
                    orderPay.setGmtModified(new Date());
                    orderPayMapper.insert(orderPay);
                });
                return;
            }
        }
        Date date = new Date();
        if (StringConstant.ALIPAY_WAIT.equals(aliPayNotifyParam.getTradeStatus())) { // 交易创建，等待买家付款
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 2);
            updateWrapper.set("order_status", 1);
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",交易创建，等待买家付款");
            updateWrapper.set("gmt_modified", date);
            updateWrapper.eq("order_parent_number", orderParentNum);
            orderMapper.update(new Order(), updateWrapper);
            return;
        } else if (StringConstant.ALIPAY_CLOSED.equals(aliPayNotifyParam.getTradeStatus())) { // 未付款交易超时关闭，或支付完成后全额退款
            // 更改当前订单支付状态为失败
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 3);
            updateWrapper.set("order_status", 1);
            updateWrapper.set("close_reason", "订单支付失败");
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",未付款交易超时关闭，或支付完成后全额退款");
            updateWrapper.set("gmt_modified", date);
            updateWrapper.eq("order_parent_number", orderParentNum);
            orderMapper.update(new Order(), updateWrapper);
            return;
        } else if (StringConstant.ALIPAY_SUCCESS.equals(aliPayNotifyParam.getTradeStatus())) {
            // 更改当前订单未支付状态
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("order_status", 2);
            updateWrapper.set("pay_status", 4);
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", aliPayNotifyParam.getGmtCreate());
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",交易支付成功");
            updateWrapper.set("gateway_order_id", aliPayNotifyParam.getTradeNo());
            updateWrapper.set("gmt_modified", date);
            updateWrapper.setSql("actual_pay_amount = total_amount");
            updateWrapper.eq("order_parent_number", orderParentNum);
            int updateCount = orderMapper.update(new Order(), updateWrapper);
            if (updateCount != orderList.size()) {
                logger.error("订单支付回调，修改状态失败，订单号：" + aliPayNotifyParam.getOutTradeNo());
                return;
            } else {
                orderList.forEach(o -> {
                    if (o.getGiftMemberCardId() != 0 && o.getGiftCardAmount().compareTo(BigDecimal.ZERO) == 1) {
                        //如果有礼品卡，则修改礼品卡状态
                        UpdateWrapper<GiftMemberCard> cardUpdateWrapper = new UpdateWrapper<>();
                        cardUpdateWrapper.setSql("gift_value_left = gift_value_left -" + o.getGiftCardAmount());
                        cardUpdateWrapper.set("gmt_modified", date);
                        cardUpdateWrapper.eq("id", o.getGiftMemberCardId());
                        cardUpdateWrapper.notIn("gift_status", 0, 3);
                        cardUpdateWrapper.ge("gift_value_left", o.getGiftCardAmount());
                        int giftCount = giftMemberCardMapper.update(new GiftMemberCard(), cardUpdateWrapper);
                        if (giftCount <= 0) {
                            logger.error("订单支付回调，修改礼品卡失败，礼品卡金额不足,订单号：" + aliPayNotifyParam.getOutTradeNo());
                        } else {
                            // 查询对应品卡
                            GiftMemberCard giftMemberCard = giftMemberCardMapper.selectById(o.getGiftMemberCardId());
                            UpdateWrapper<GiftMemberCard> giftMemberCardUpdateWrapper = new UpdateWrapper<>();
                            if (giftMemberCard.getGiftValueLeft().compareTo(BigDecimal.ONE) <= 0) {
                                giftMemberCardUpdateWrapper.set("gift_status", 3);
                            } else {
                                if (giftMemberCard.getGiftStatus() == 1) {
                                    giftMemberCardUpdateWrapper.set("gift_status", 2);
                                }
                            }
                            giftMemberCardUpdateWrapper.set("gmt_modified", date);
                            giftMemberCardUpdateWrapper.eq("id", giftMemberCard.getId());
                            giftMemberCardMapper.update(new GiftMemberCard(), giftMemberCardUpdateWrapper);
                            GiftMemberCardRecord giftMemberCardRecord = new GiftMemberCardRecord();
                            giftMemberCardRecord.setGiftMemberCardId(o.getGiftMemberCardId());
                            giftMemberCardRecord.setMemberId(o.getMemberId());
                            giftMemberCardRecord.setOrderType(o.getOrderType());
                            giftMemberCardRecord.setUseMemberId(giftMemberCard.getUseMemberId());
                            giftMemberCardRecord.setGiftCardId(giftMemberCard.getGiftBatchCardId());
                            giftMemberCardRecord.setOrderId(o.getId());
                            giftMemberCardRecord.setOrderAmount(o.getGiftCardAmount());
                            giftMemberCardRecord.setGiftValueLeft(giftMemberCard.getGiftValueLeft());
                            giftMemberCardRecord.setGiftValueNow(giftMemberCard.getGiftValueLeft());
                            giftMemberCardRecord.setGiftValueUse(giftMemberCard.getGiftValue().subtract(giftMemberCard.getGiftValueLeft()));
                            giftMemberCardRecord.setIsDelete(0);
                            giftMemberCardRecord.setGmtCreate(date);
                            giftMemberCardRecord.setGmtModified(date);
                            memberCardRecordMapper.insert(giftMemberCardRecord);
                        }
                    }
                    // 普通商品发送消息
                    if (o.getOrderProductType() == 1) {
                        ShopProductStockManagerParam shopProductStockManagerParam = new ShopProductStockManagerParam();
                        shopProductStockManagerParam.setType(1);
                        shopProductStockManagerParam.setOrderNum(o.getOrderNumber());
                        this.orderStock(shopProductStockManagerParam);
                    } else if (o.getOrderProductType() == 2) {
                        // 处理对应会员卡信息
                        giftCardCreateService.giftCardMemberCreate(o.getOrderNumber());
                    }
                });
            }
        } else {
            return;
        }
        // 添加商城订单支付表
        orderList.forEach(o -> {
            OrderPay orderPay = new OrderPay();
            orderPay.setOrderId(o.getId());
            orderPay.setType(1);
            orderPay.setPayTypeId(1);
            orderPay.setPayNumber(aliPayNotifyParam.getTradeNo());
            orderPay.setPayStatus(aliPayNotifyParam.getTradeStatus() == StringConstant.ALIPAY_SUCCESS ? 0 : 1);
//            orderPay.setPayRemark(aliPayNotifyParam.getTradeStatus());
            orderPay.setGmtCreate(new Date());
            orderPay.setGmtModified(new Date());
            orderPayMapper.insert(orderPay);
        });
        logger.info("订单支付回调，正常完成，订单号：" + aliPayNotifyParam.getOutTradeNo());
    }


    private void weChatSuccessNotify(ShopProductStockManagerParam stockManagerParam) {
        WxPayOrderNotifyResult wxPayOrderNotifyResult = JSONObject.parseObject(stockManagerParam.getXmldata(), WxPayOrderNotifyResult.class);
        wxPayOrderNotifyResultDao.insert(wxPayOrderNotifyResult);
        if (wxPayOrderNotifyResult == null) {
            logger.error("订单支付回调，获取回调信息为空，回调信息：" + stockManagerParam.getXmldata());
            return;
        }
        // 获取对应商品父订单
        String[] orderNum = wxPayOrderNotifyResult.getAttach().split(",");
        List<String> orderNumList = Arrays.asList(orderNum);
        // 查询当前订单
        // 获取对应商品父订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.in("order_number", orderNumList);
        orderQueryWrapper.eq("is_delete", 0);
        List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
        if (orderList == null || orderList.isEmpty() || orderNumList.size() != orderList.size()) {
            logger.error("订单支付回调，查询原有订单失败，订单号：" + wxPayOrderNotifyResult.getAttach());
            return;
        } else {
            List<Integer> orderIdList = orderList.stream().map(order -> order.getId()).collect(Collectors.toList());
            // 查询是否已经执行过了
            QueryWrapper<OrderPay> payQueryWrapper = new QueryWrapper<>();
            payQueryWrapper.in("order_id", orderIdList);
            payQueryWrapper.eq("type", 1);
            int orderPayCount = orderPayMapper.selectCount(payQueryWrapper);
            if (orderPayCount == orderNumList.size()) {
                logger.error("订单支付回调，当前订单已经执行，订单号：" + wxPayOrderNotifyResult.getAttach());
                return;
            }
            // 检查当前订单金额是否一致
            BigDecimal totalAmount = orderList.stream().map(Order::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            Integer totalAmountInt = totalAmount.multiply(BigDecimal.valueOf(100)).intValue();
            if (!totalAmountInt.equals(wxPayOrderNotifyResult.getTotalFee())) {
                logger.error("订单支付回调，支付金额和入参金额不一致，订单号" + wxPayOrderNotifyResult.getAttach());
                // 添加商城订单支付表
                orderList.forEach(o -> {
                    OrderPay orderPay = new OrderPay();
                    orderPay.setOrderId(o.getId());
                    orderPay.setPayTypeId(1);
                    orderPay.setType(1);
                    orderPay.setPayNumber(wxPayOrderNotifyResult.getTransactionId());
                    orderPay.setPayStatus(1);
                    orderPay.setPayRemark("支付金额不一致");
                    orderPay.setGmtCreate(new Date());
                    orderPay.setGmtModified(new Date());
                    orderPayMapper.insert(orderPay);
                });
                return;
            }
        }
        Date date = new Date();
        if (StringConstant.WECHAT_FAIL.equals(wxPayOrderNotifyResult.getResultCode())) {
            // 更改当前订单支付状态为失败
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 3);
            updateWrapper.set("order_status", 6);
            updateWrapper.set("close_reason", "订单支付失败");
            updateWrapper.set("pay_type_id", 1);
            updateWrapper.set("pay_type_name", "wechat");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", wxPayOrderNotifyResult.getErrCode() + "," + wxPayOrderNotifyResult.getErrCodeDes());
            updateWrapper.set("gmt_modified", date);
            updateWrapper.in("order_number", orderNumList);
            orderMapper.update(new Order(), updateWrapper);
            return;
        } else if (StringConstant.WECHAT_SUCCESS.equals(wxPayOrderNotifyResult.getResultCode())) {

            // 更改当前订单未支付状态
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("order_status", 2);
            updateWrapper.set("pay_status", 4);
            updateWrapper.set("pay_type_id", 1);
            updateWrapper.set("pay_type_name", "wechat");
            updateWrapper.set("pay_date", wxPayOrderNotifyResult.getTimeEnd());
            updateWrapper.set("pay_remark", wxPayOrderNotifyResult.getReturnMsg());
            updateWrapper.set("gateway_order_id", wxPayOrderNotifyResult.getTransactionId());
            updateWrapper.set("gmt_modified", date);
            updateWrapper.setSql("actual_pay_amount = total_amount");
            updateWrapper.in("order_number", orderNumList);
            int updateCount = orderMapper.update(new Order(), updateWrapper);
            if (updateCount != orderNumList.size()) {
                logger.error("订单支付回调，修改状态失败，订单号：" + wxPayOrderNotifyResult.getAttach());
                return;
            } else {
                orderList.forEach(o -> {
                    if (o.getGiftMemberCardId() != 0 && o.getGiftCardAmount().compareTo(BigDecimal.ZERO) == 1) {
                        //如果有礼品卡，则修改礼品卡状态
                        UpdateWrapper<GiftMemberCard> cardUpdateWrapper = new UpdateWrapper<>();
                        cardUpdateWrapper.setSql("gift_value_left = gift_value_left -" + o.getGiftCardAmount());
                        cardUpdateWrapper.set("gmt_modified", date);
                        cardUpdateWrapper.eq("id", o.getGiftMemberCardId());
                        cardUpdateWrapper.notIn("gift_status", 0, 3);
                        cardUpdateWrapper.ge("gift_value_left", o.getGiftCardAmount());
                        int giftCount = giftMemberCardMapper.update(new GiftMemberCard(), cardUpdateWrapper);
                        if (giftCount <= 0) {
                            logger.error("订单支付回调，修改礼品卡失败，礼品卡金额不足,订单号：" + wxPayOrderNotifyResult.getAttach());
                        } else {
                            // 查询对应品卡
                            GiftMemberCard giftMemberCard = giftMemberCardMapper.selectById(o.getGiftMemberCardId());
                            UpdateWrapper<GiftMemberCard> giftMemberCardUpdateWrapper = new UpdateWrapper<>();
                            if (giftMemberCard.getGiftValueLeft().compareTo(BigDecimal.ONE) <= 0) {
                                giftMemberCardUpdateWrapper.set("gift_status", 3);
                            } else {
                                if (giftMemberCard.getGiftStatus() == 1) {
                                    giftMemberCardUpdateWrapper.set("gift_status", 2);
                                }
                            }
                            giftMemberCardUpdateWrapper.set("gmt_modified", date);
                            giftMemberCardUpdateWrapper.eq("id", giftMemberCard.getId());
                            giftMemberCardMapper.update(new GiftMemberCard(), giftMemberCardUpdateWrapper);
                            GiftMemberCardRecord giftMemberCardRecord = new GiftMemberCardRecord();
                            giftMemberCardRecord.setGiftMemberCardId(o.getGiftMemberCardId());
                            giftMemberCardRecord.setMemberId(o.getMemberId());
                            giftMemberCardRecord.setOrderType(o.getOrderType());
                            giftMemberCardRecord.setUseMemberId(giftMemberCard.getUseMemberId());
                            giftMemberCardRecord.setGiftCardId(giftMemberCard.getGiftBatchCardId());
                            giftMemberCardRecord.setOrderId(o.getId());
                            giftMemberCardRecord.setOrderAmount(o.getGiftCardAmount());
                            giftMemberCardRecord.setGiftValueLeft(giftMemberCard.getGiftValueLeft());
                            giftMemberCardRecord.setGiftValueNow(giftMemberCard.getGiftValueLeft());
                            giftMemberCardRecord.setGiftValueUse(giftMemberCard.getGiftValue().subtract(giftMemberCard.getGiftValueLeft()));
                            giftMemberCardRecord.setIsDelete(0);
                            giftMemberCardRecord.setGmtCreate(date);
                            giftMemberCardRecord.setGmtModified(date);
                            memberCardRecordMapper.insert(giftMemberCardRecord);
                        }
                    }
                    // 普通商品发送消息
                    if (o.getOrderProductType() == 1) {
                        ShopProductStockManagerParam shopProductStockManagerParam = new ShopProductStockManagerParam();
                        shopProductStockManagerParam.setType(1);
                        shopProductStockManagerParam.setOrderNum(o.getOrderNumber());
                        this.orderStock(shopProductStockManagerParam);
                    } else if (o.getOrderProductType() == 2) {
                        // 处理对应会员卡信息
                        giftCardCreateService.giftCardMemberCreate(o.getOrderNumber());
                    }
                });
            }
        } else {
            return;
        }
        // 添加商城订单支付表
        orderList.forEach(o -> {
            OrderPay orderPay = new OrderPay();
            orderPay.setOrderId(o.getId());
            orderPay.setType(1);
            orderPay.setPayTypeId(1);
            orderPay.setPayNumber(wxPayOrderNotifyResult.getTransactionId());
            orderPay.setPayStatus(wxPayOrderNotifyResult.getResultCode() == "SUCCESS" ? 0 : 1);
            orderPay.setPayRemark(wxPayOrderNotifyResult.getReturnMsg());
            orderPay.setGmtCreate(new Date());
            orderPay.setGmtModified(new Date());
            orderPayMapper.insert(orderPay);
        });
        logger.info("订单支付回调，正常完成，订单号：" + wxPayOrderNotifyResult.getAttach());
    }


    private void orderCancel(ShopProductStockManagerParam stockManagerParam) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<Order>();
        orderQueryWrapper.eq("id", stockManagerParam.getOrderId());
        orderQueryWrapper.eq("order_number", stockManagerParam.getOrderNum());
        orderQueryWrapper.eq("is_delete", 0);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if (order == null) {
            logger.error("订单取消，查询不到当前订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
        }
        Date date = new Date();
        if (order.getOrderStatus() == 1) {
            //订单已经到时间
            Order orderUpadate = new Order();
            orderUpadate.setId(order.getId());
            orderUpadate.setOrderStatus(6);
            orderUpadate.setCloseReason("订单已取消");
            orderUpadate.setGmtModified(date);
            orderMapper.updateById(orderUpadate);
            //更新orderItems
            QueryWrapper<OrderItems> itemsQueryWrapper = new QueryWrapper<OrderItems>();
            itemsQueryWrapper.eq("order_id", stockManagerParam.getOrderId());
            itemsQueryWrapper.eq("is_delete", 0);
            List<OrderItems> orderItemsList = orderItemsMapper.selectList(itemsQueryWrapper);
            if (orderItemsList == null || orderItemsList.isEmpty()) {
                logger.error("订单取消，查询不到对应子订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
                return;
            }
            orderItemsList.stream().forEach(o -> {
                shopProductSkuReturn(date, o);
            });
        } else {
            logger.info("订单取消，当前订单状态不符合关闭。订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
        }
    }

    private void orderTimeOut(ShopProductStockManagerParam stockManagerParam) {
        //关闭订单，删除对应子订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<Order>();
        orderQueryWrapper.eq("id", stockManagerParam.getOrderId());
        orderQueryWrapper.eq("order_number", stockManagerParam.getOrderNum());
        orderQueryWrapper.eq("is_delete", 0);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if (order == null) {
            logger.error("订单超时关闭，查询不到当前订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        Date date = new Date();
        if (order.getOrderStatus() == 1) {
            //订单已经到时间
            Order orderUpadate = new Order();
            orderUpadate.setId(order.getId());
            orderUpadate.setOrderStatus(6);
            orderUpadate.setCloseReason("超时未付款，订单已关闭");
            orderUpadate.setGmtModified(date);
            orderMapper.updateById(orderUpadate);
            //更新优惠券退回
            if (!DataUtils.EmptyOrNegativeOrZero(order.getCouponId())) {
                returnCoupon(order.getCouponId());
            }
            //更新orderItems
            QueryWrapper<OrderItems> itemsQueryWrapper = new QueryWrapper<OrderItems>();
            itemsQueryWrapper.eq("order_id", stockManagerParam.getOrderId());
            itemsQueryWrapper.eq("is_delete", 0);
            List<OrderItems> orderItemsList = orderItemsMapper.selectList(itemsQueryWrapper);
            if (orderItemsList == null || orderItemsList.isEmpty()) {
                logger.error("订单超时关闭，查询不到对应子订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
                return;
            }
            if (stockManagerParam.getSubType() == 1) {
                orderItemsList.stream().forEach(o -> {
                    shopProductSkuReturn(date, o);
                });
            }
        } else {
            logger.info("订单超时关闭，当前订单状态不符合关闭。订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
        }
    }

    private void orderStock(ShopProductStockManagerParam stockManagerParam) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<Order>();
        orderQueryWrapper.eq("order_number", stockManagerParam.getOrderNum());
        orderQueryWrapper.eq("is_delete", 0);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if (order == null) {
            logger.error("查询不到当前订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        } else {
            if (order.getPayStatus() != 4 && order.getOrderStatus() != 2) {
                logger.error("查询当前订单状态错误，订单id:" + stockManagerParam.getOrderId() + ",支付状态：" + order.getPayStatus() + ",订单状态：" + order.getOrderStatus());
            }
        }
        QueryWrapper<OrderItems> itemsQueryWrapper = new QueryWrapper<OrderItems>();
        itemsQueryWrapper.eq("order_id", order.getId());
        itemsQueryWrapper.eq("is_delete", 0);
        List<OrderItems> orderItemsList = orderItemsMapper.selectList(itemsQueryWrapper);
        if (orderItemsList == null || orderItemsList.isEmpty()) {
            createFailueOrder(order.getId());
            logger.error("当前订单无商品，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        //参与优惠金额数量
        BigDecimal preferentialAmount = orderItemsList.stream().filter(o -> o.getCouponId() != 0).map(o -> o.getShopTotalAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        List<OrderItems> orderItemsListNew = orderItemsList.stream().map(o -> {
            QueryWrapper<ShopSpecificationSku> skuQueryWrapper = new QueryWrapper<ShopSpecificationSku>();
            skuQueryWrapper.eq("id", o.getShopSpecificationSkuId());
            skuQueryWrapper.eq("sku_id", o.getShopSpecificationSkuSkuId());
            skuQueryWrapper.eq("is_deleted", 0);
            skuQueryWrapper.eq("type", 1);
            ShopSpecificationSku shopSpecificationSku = specificationSkuMapper.selectOne(skuQueryWrapper);
            if (shopSpecificationSku == null || shopSpecificationSku.getStock() < o.getPurchaseQuantity()) {
                o.setIsDelete(1);
            }
            return o;
        }).filter(o -> o.getIsDelete() == 0).collect(Collectors.toList());
        if (orderItemsListNew.size() != orderItemsList.size()) {
            // 创建失败订单
            createFailueOrder(order.getId());
            // 回退优惠券
            returnCoupon(order.getCouponId());
            logger.error("当前订单有商品库存不足，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        //更新mysql信息
        int indexOrderItems = 0;
        BigDecimal tmpSubAmount = BigDecimal.ZERO;
        for (OrderItems o : orderItemsListNew) {
            indexOrderItems++;
            UpdateWrapper<ShopSpecificationSku> skuUpdateWrapper = new UpdateWrapper<ShopSpecificationSku>();
            skuUpdateWrapper.setSql("stock = stock -" + o.getPurchaseQuantity());
            skuUpdateWrapper.eq("id", o.getShopSpecificationSkuId());
            skuUpdateWrapper.eq("sku_id", o.getShopSpecificationSkuSkuId());
            skuUpdateWrapper.eq("is_deleted", 0);
            skuUpdateWrapper.ge("stock", 0);
            int updateCount = specificationSkuMapper.update(new ShopSpecificationSku(), skuUpdateWrapper);
            if (updateCount >= 1) {
                UpdateWrapper<ShopProduct> updateWrapper = new UpdateWrapper<ShopProduct>();
                updateWrapper.setSql("stock = stock - " + o.getPurchaseQuantity());
                updateWrapper.setSql("sale_count = sale_count + " + o.getPurchaseQuantity());
                updateWrapper.eq("id", o.getShopProductId());
                updateWrapper.ge("stock", 0);
                int shopCount = shopProductMapper.update(new ShopProduct(), updateWrapper);
                if (shopCount <= 0) {
                    QueryWrapper<ShopProduct> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("id", o.getShopProductId());
                    queryWrapper.select("id", "stock");
                    ShopProduct shopProduct = shopProductMapper.selectOne(queryWrapper);
                    if (shopProduct != null) {
                        if (shopProduct.getStock() <= 0) {
                            //判断是否库存已经没了，修改状态为已售罄
                            UpdateWrapper<ShopProduct> productUpdateWrapper = new UpdateWrapper<ShopProduct>();
                            productUpdateWrapper.eq("id", shopProduct.getId());
                            productUpdateWrapper.ge("stock", 0);
                            productUpdateWrapper.set("sale_status", 1);
                            shopProductMapper.update(new ShopProduct(), productUpdateWrapper);
                        }
                    }
                }
                // 判断是否是秒杀活动，如果是秒杀活动则修改对应秒杀活动
                if (o.getShopActiveType() == 1) {
                    UpdateWrapper<SpikeActiveShop> shopUpdateWrapper = new UpdateWrapper<>();
                    shopUpdateWrapper.setSql("stock = stock - " + o.getPurchaseQuantity());
                    shopUpdateWrapper.setSql("sale_count = sale_count + " + o.getPurchaseQuantity());
                    shopUpdateWrapper.eq("is_deleted", 0);
                    shopUpdateWrapper.eq("id", o.getShopActiveId());
                    shopUpdateWrapper.ge("stock", 0);
                    spikeActiveShopMapper.update(new SpikeActiveShop(), shopUpdateWrapper);
                }
            }
            // 计算平摊每个金额实际分摊金额
            OrderItems orderItems = new OrderItems();
            orderItems.setId(o.getId());
            if (o.getCouponId() != 0) {
                //如果当前是最后一项，不计算，直接相减获取，去除小数点
                BigDecimal subAmount = BigDecimal.ZERO;
                if (indexOrderItems == orderItemsListNew.size()) {
                    subAmount = order.getDiscountAmount().subtract(tmpSubAmount);

                } else {
                    subAmount = order.getDiscountAmount().multiply(o.getShopTotalAmount().divide(preferentialAmount, 2, BigDecimal.ROUND_HALF_DOWN)).setScale(2);
                    tmpSubAmount = tmpSubAmount.add(subAmount);
                }
                BigDecimal realAmount = o.getShopTotalAmount().subtract(subAmount);
                orderItems.setRealTotalPrice(realAmount);
                orderItems.setEnabledRefundAmount(realAmount);
            } else {
                orderItems.setRealTotalPrice(o.getShopTotalAmount());
                orderItems.setEnabledRefundAmount(o.getShopTotalAmount());
            }
            orderItemsMapper.updateById(orderItems);
        }
        //更新订单状态
        Order orderNew = new Order();
        orderNew.setId(order.getId());
        orderNew.setGmtModified(new Date());
        orderNew.setIsOutTreasury(1);
        orderNew.setOrderStatus(3);
        orderMapper.updateById(orderNew);
        //更新优惠券信息
        if (!DataUtils.EmptyOrNegativeOrZero(order.getCouponId())) {
            CouponMemberRecord couponMemberRecord = new CouponMemberRecord();
            couponMemberRecord.setId(order.getCouponId());
            couponMemberRecord.setIsUse(1);
            couponMemberRecord.setGmtModified(new Date());
            couponMemberRecordMapper.updateById(couponMemberRecord);
        }
    }

    private void shopProductSkuReturn(Date date, OrderItems o) {
        UpdateOperations<ShopSkuModel> updateOperations = shopSkuModelDao.createUpdateOperations();
        updateOperations.inc("stock", o.getPurchaseQuantity());
        updateOperations.set("gmtModified", date);
        Query<ShopSkuModel> skuModelQuery = shopSkuModelDao.createQuery(ShopSkuModel.class);
        skuModelQuery.field("shopSpecificationSkuId").equal(o.getShopSpecificationSkuId());
        skuModelQuery.field("type").equal(1);
        int updateCount = shopSkuModelDao.update(skuModelQuery, updateOperations).getUpdatedCount();
        if (updateCount <= 0) {
            logger.error("订单超时回mongo库存失败，商品主键id:" + o.getShopProductId() + ",回库数量：" + o.getPurchaseQuantity());
        }
    }


    private void createFailueOrder(Integer orderId) {
        Order orderNew = new Order();
        orderNew.setOrderStatus(6);
        orderNew.setId(orderId);
        orderNew.setGmtModified(new Date());
        orderNew.setCloseReason("商品出库失败");
        orderMapper.updateById(orderNew);
        // TODO: 2018/11/4 后续补回走退款流程
    }

    private void returnCoupon(Integer couponId) {
        CouponMemberRecord couponMemberRecord = new CouponMemberRecord();
        couponMemberRecord.setId(couponId);
        couponMemberRecord.setIsUse(0);
        couponMemberRecord.setGmtModified(new Date());
        couponMemberRecordMapper.updateById(couponMemberRecord);
    }
}
